<template>
  <div class="login-bg">
    <div id="login-container">
      <h2 style="text-align: center; margin-top: 0">图书借阅系统</h2>
      <el-form
        ref="form"
        :model="form"
        @submit.native.prevent="handleLogin"
        :rules="rules"
      >
        <el-form-item prop="username">
          <el-input
            v-model="form.username"
            placeholder="请输入用户名"
            clearable
            prefix-icon="el-icon-user"
          ></el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="form.password"
            placeholder="请输入密码"
            clearable
            show-password
            prefix-icon="el-icon-lock"
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            native-type="submit"
            style="
              width: 100%;
              height: 40px;
              display: flex;
              align-items: center;
              justify-content: center;
            "
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>
      <div style="text-align: center; margin-top: 10px">
        还没有账号？<router-link to="/register">立即注册</router-link>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "loginPage",
  data() {
    return {
      form: {
        username: "",
        password: "",
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
    };
  },
  methods: {
    handleLogin() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.submit();
        }
      });
    },
    async submit() {
      const formData = new FormData();
      formData.append("username", this.form.username);
      formData.append("password", this.form.password);
      const response = await this.$request.post("/api/auth/login", formData);
      if (response.code == 200) {
        localStorage.setItem("token", response.data.token);
        localStorage.setItem("username", response.data.username);
        this.$router.push("/home");
      } else {
        this.$message.error(response.message);
      }
    },
  },
};
</script>

<style scoped>
.login-bg {
  background: url("@/assets/login.jpg") no-repeat center center/cover;
  z-index: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  margin: 0;
}

#login-container {
  z-index: 1;
  width: 400px;
  padding: 30px;
  background-color: rgba(255, 255, 255, 0.9);
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.el-form-item {
  margin-bottom: 15px;
}

.el-form-item__label {
  line-height: 32px;
}

.el-input__prefix {
  color: rgba(0, 0, 0, 0.25);
}
</style>